<template>
  <div class="admin-dashboard min-h-screen" style="background-color: #FAF9F5;">
    <!-- 页面头部 -->
    <div class="mb-6 p-6">
      <h1 class="text-2xl font-bold text-gray-900">管理后台</h1>
      <p class="text-gray-600 mt-1">欢迎回来，{{ userInfo?.name || '管理员' }}！今天是 {{ currentDate }}</p>
    </div>

    <!-- 统计卡片区域 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 px-6">
      <!-- 学生总数 -->
      <div class="rounded-[0.6rem] p-6 border border-gray-200 bg-gradient-to-r from-blue-500 to-blue-600 text-white" style="box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-blue-100 text-sm font-medium">学生总数</p>
            <p class="text-3xl font-bold mt-1">{{ statistics?.totalStudents || 0 }}</p>
            <p class="text-blue-100 text-xs mt-2">
              <span class="inline-flex items-center">
                <i class="icon-[heroicons--arrow-trending-up] w-3 h-3 mr-1"></i>
                较昨日 +{{ statistics?.newStudentsToday || 0 }}
              </span>
            </p>
          </div>
          <div class="bg-white bg-opacity-20 rounded-[0.6rem] p-3">
            <i class="icon-[heroicons--user-group] w-8 h-8"></i>
          </div>
        </div>
      </div>

      <!-- 已报到学生 -->
      <div class="rounded-[0.6rem] p-6 border border-gray-200 bg-gradient-to-r from-green-500 to-green-600 text-white" style="box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-green-100 text-sm font-medium">已报到学生</p>
            <p class="text-3xl font-bold mt-1">{{ statistics?.registeredStudents || 0 }}</p>
            <p class="text-green-100 text-xs mt-2">
              <span class="inline-flex items-center">
                报到率 {{ registrationRate }}%
              </span>
            </p>
          </div>
          <div class="bg-white bg-opacity-20 rounded-[0.6rem] p-3">
            <i class="icon-[heroicons--check-circle] w-8 h-8"></i>
          </div>
        </div>
      </div>

      <!-- 缴费完成率 -->
      <div class="rounded-[0.6rem] p-6 border border-gray-200 bg-gradient-to-r from-yellow-500 to-yellow-600 text-white" style="box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-yellow-100 text-sm font-medium">缴费完成</p>
            <p class="text-3xl font-bold mt-1">{{ paymentRate }}%</p>
            <p class="text-yellow-100 text-xs mt-2">
              <span class="inline-flex items-center">
                金额 ¥{{ formatMoney(statistics?.totalPaymentAmount || 0) }}
              </span>
            </p>
          </div>
          <div class="bg-white bg-opacity-20 rounded-[0.6rem] p-3">
            <i class="icon-[heroicons--currency-yen] w-8 h-8"></i>
          </div>
        </div>
      </div>

      <!-- 宿舍入住率 -->
      <div class="rounded-[0.6rem] p-6 border border-gray-200 bg-gradient-to-r from-purple-500 to-purple-600 text-white" style="box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-purple-100 text-sm font-medium">宿舍入住率</p>
            <p class="text-3xl font-bold mt-1">{{ statistics?.dormitoryOccupancyRate || 0 }}%</p>
            <p class="text-purple-100 text-xs mt-2">
              <span class="inline-flex items-center">
                已分配 {{ statistics?.assignedDormitories || 0 }} 间
              </span>
            </p>
          </div>
          <div class="bg-white bg-opacity-20 rounded-[0.6rem] p-3">
            <i class="icon-[heroicons--home] w-8 h-8"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表和数据展示区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8 px-6">
      <!-- 报到趋势图 -->
      <div class="rounded-[0.6rem] p-6 border border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">报到趋势</h3>
          <div class="flex items-center space-x-2">
            <button
              v-for="period in chartPeriods"
              :key="period.value"
              @click="selectedPeriod = period.value"
              :class="[
                'px-3 py-1 text-xs rounded-[0.6rem] transition-colors border',
                selectedPeriod === period.value
                  ? 'text-gray-900 border-gray-300 font-semibold'
                  : 'text-gray-600 border-gray-200 hover:text-gray-900 hover:border-gray-300'
              ]"
              :style="selectedPeriod === period.value ? 'background-color: #FAF9F5;' : 'background-color: #F5F5F0;'"
            >
              {{ period.label }}
            </button>
          </div>
        </div>
        <div class="h-64" ref="registrationChartRef"></div>
      </div>

      <!-- 专业分布饼图 -->
      <div class="rounded-lg p-6 border border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">专业分布</h3>
          <span class="text-sm text-gray-500">共 {{ statistics?.totalMajors || 0 }} 个专业</span>
        </div>
        <div class="h-64" ref="majorChartRef"></div>
      </div>
    </div>

    <!-- 缴费统计和最新动态 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 px-6">
      <!-- 缴费统计柱状图 -->
      <div class="lg:col-span-2 rounded-lg p-6 border border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">缴费统计</h3>
          <div class="text-sm text-gray-500">
            总金额: ¥{{ formatMoney(statistics?.totalPaymentAmount || 0) }}
          </div>
        </div>
        <div class="h-64" ref="paymentChartRef"></div>
      </div>

      <!-- 最新动态 -->
      <div class="rounded-lg p-6 border border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">最新动态</h3>
          <router-link 
            to="/admin/notices" 
            class="text-sm text-blue-600 hover:text-blue-700"
          >
            查看全部
          </router-link>
        </div>
        
        <div class="space-y-4">
          <div 
            v-for="activity in recentActivities" 
            :key="activity.id"
            class="flex items-start space-x-3 p-3 rounded-lg border border-gray-200"
            style="background-color: #F5F5F0;"
          >
            <div :class="[
              'w-2 h-2 rounded-full mt-2 flex-shrink-0',
              activity.type === 'registration' ? 'bg-green-500' :
              activity.type === 'payment' ? 'bg-yellow-500' :
              activity.type === 'dormitory' ? 'bg-purple-500' : 'bg-blue-500'
            ]"></div>
            <div class="flex-1 min-w-0">
              <p class="text-sm font-medium text-gray-900 truncate">
                {{ activity.title }}
              </p>
              <p class="text-xs text-gray-500 mt-1">
                {{ activity.description }}
              </p>
              <p class="text-xs text-gray-400 mt-1">
                {{ formatTime(activity.createdAt) }}
              </p>
            </div>
          </div>
          
          <div v-if="!recentActivities.length" class="text-center py-4">
            <i class="icon-[heroicons--document-text] w-8 h-8 text-gray-400 mx-auto mb-2"></i>
            <p class="text-sm text-gray-500">暂无最新动态</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作区域 -->
    <div class="mt-8 px-6 pb-6">
      <h3 class="text-lg font-semibold text-gray-900 mb-4">快捷操作</h3>
      <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <router-link
          v-for="action in quickActions"
          :key="action.key"
          :to="action.to"
          class="block p-4 rounded-[0.6rem] border border-gray-300 hover:border-gray-400 hover:bg-gray-100 transition-all duration-200 active:scale-[0.985]"
          style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);"
        >
          <div class="text-center">
            <div :class="[
              'w-12 h-12 rounded-lg flex items-center justify-center mx-auto mb-3',
              action.bgColor
            ]">
              <i :class="[action.icon, 'w-6 h-6', action.iconColor]"></i>
            </div>
            <p class="text-sm font-medium text-gray-900">{{ action.label }}</p>
            <p class="text-xs text-gray-500 mt-1">{{ action.description }}</p>
          </div>
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useAuthStore } from '../../stores/auth'
import { useAdminStore } from '../../stores/admin'
import { useAppStore } from '../../stores/app'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'

// 配置dayjs插件
dayjs.extend(relativeTime)

// 使用stores
const authStore = useAuthStore()
const adminStore = useAdminStore()
const appStore = useAppStore()

// 响应式数据
const selectedPeriod = ref('7d')
const registrationChartRef = ref(null)
const majorChartRef = ref(null)
const paymentChartRef = ref(null)

// 图表实例
let registrationChart = null
let majorChart = null
let paymentChart = null

// 计算属性
const userInfo = computed(() => authStore.userInfo)
const statistics = computed(() => adminStore.statistics)
const registrationRate = computed(() => adminStore.registrationRate)
const paymentRate = computed(() => adminStore.paymentRate)

const currentDate = computed(() => {
  return dayjs().format('YYYY年MM月DD日 dddd')
})

// 图表时间周期选项
const chartPeriods = [
  { label: '7天', value: '7d' },
  { label: '30天', value: '30d' },
  { label: '90天', value: '90d' }
]

// 模拟最新动态数据
const recentActivities = ref([
  {
    id: 1,
    type: 'registration',
    title: '新生报到',
    description: '张三完成了报到手续',
    createdAt: new Date(Date.now() - 5 * 60 * 1000)
  },
  {
    id: 2,
    type: 'payment',
    title: '缴费完成',
    description: '李四完成了学费缴纳',
    createdAt: new Date(Date.now() - 15 * 60 * 1000)
  },
  {
    id: 3,
    type: 'dormitory',
    title: '宿舍分配',
    description: '王五被分配到紫荆1号楼302室',
    createdAt: new Date(Date.now() - 30 * 60 * 1000)
  },
  {
    id: 4,
    type: 'notice',
    title: '通知发布',
    description: '发布了新的报到须知',
    createdAt: new Date(Date.now() - 60 * 60 * 1000)
  }
])

// 快捷操作
const quickActions = [
  {
    key: 'students',
    label: '学生管理',
    description: '查看学生信息',
    icon: 'icon-[heroicons--user-group]',
    bgColor: 'bg-blue-100',
    iconColor: 'text-blue-600',
    to: '/admin/students'
  },
  {
    key: 'registration',
    label: '报到管理',
    description: '管理报到流程',
    icon: 'icon-[heroicons--check-circle]',
    bgColor: 'bg-green-100',
    iconColor: 'text-green-600',
    to: '/admin/registration'
  },
  {
    key: 'dormitory',
    label: '宿舍管理',
    description: '分配宿舍',
    icon: 'icon-[heroicons--home]',
    bgColor: 'bg-purple-100',
    iconColor: 'text-purple-600',
    to: '/admin/dormitory'
  },
  {
    key: 'finance',
    label: '财务管理',
    description: '缴费统计',
    icon: 'icon-[heroicons--currency-yen]',
    bgColor: 'bg-yellow-100',
    iconColor: 'text-yellow-600',
    to: '/admin/finance'
  },
  {
    key: 'notices',
    label: '通知公告',
    description: '发布通知',
    icon: 'icon-[heroicons--megaphone]',
    bgColor: 'bg-red-100',
    iconColor: 'text-red-600',
    to: '/admin/notices'
  },
  {
    key: 'settings',
    label: '系统设置',
    description: '配置系统',
    icon: 'icon-[heroicons--cog-6-tooth]',
    bgColor: 'bg-gray-100',
    iconColor: 'text-gray-600',
    to: '/admin/settings'
  }
]

// 方法
const formatMoney = (amount) => {
  return (amount / 10000).toFixed(1) + '万'
}

const formatTime = (time) => {
  return dayjs(time).fromNow()
}

// 初始化报到趋势图
const initRegistrationChart = () => {
  if (!registrationChartRef.value) return
  
  registrationChart = echarts.init(registrationChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['09-01', '09-02', '09-03', '09-04', '09-05', '09-06', '09-07']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '报到人数',
        type: 'line',
        smooth: true,
        data: [120, 132, 101, 134, 90, 230, 210],
        itemStyle: {
          color: '#3B82F6'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(59, 130, 246, 0.3)' },
              { offset: 1, color: 'rgba(59, 130, 246, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  
  registrationChart.setOption(option)
}

// 初始化专业分布饼图
const initMajorChart = () => {
  if (!majorChartRef.value) return
  
  majorChart = echarts.init(majorChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '专业分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 335, name: '计算机科学与技术' },
          { value: 310, name: '软件工程' },
          { value: 234, name: '数据科学与大数据技术' },
          { value: 135, name: '人工智能' },
          { value: 148, name: '网络工程' }
        ]
      }
    ]
  }
  
  majorChart.setOption(option)
}

// 初始化缴费统计柱状图
const initPaymentChart = () => {
  if (!paymentChartRef.value) return
  
  paymentChart = echarts.init(paymentChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['学费', '住宿费', '体检费', '保险费', '教材费']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}万'
      }
    },
    series: [
      {
        name: '应收金额',
        type: 'bar',
        data: [1200, 300, 80, 150, 200],
        itemStyle: {
          color: '#E5E7EB'
        }
      },
      {
        name: '已收金额',
        type: 'bar',
        data: [1000, 250, 70, 120, 180],
        itemStyle: {
          color: '#3B82F6'
        }
      }
    ]
  }
  
  paymentChart.setOption(option)
}

// 初始化所有图表
const initCharts = async () => {
  await nextTick()
  initRegistrationChart()
  initMajorChart()
  initPaymentChart()
}

// 窗口大小变化时重新调整图表
const handleResize = () => {
  registrationChart?.resize()
  majorChart?.resize()
  paymentChart?.resize()
}

// 生命周期
onMounted(async () => {
  // 设置页面标题
  appStore.setPageTitle('管理后台')
  
  // 初始化管理员数据
  await adminStore.initAdminData()
  
  // 初始化图表
  await initCharts()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  registrationChart?.dispose()
  majorChart?.dispose()
  paymentChart?.dispose()
})
</script>

<style scoped>
@reference "tailwindcss";
.admin-dashboard {
  @apply p-6;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .admin-dashboard {
    @apply p-4;
  }
}
</style>